package info.xiao.dataStructrue.array;

import java.util.HashMap;
import java.util.Map;

/**
 * @Classname TwoSum 两数之和
 * @Description 链接: https://leetcode.cn/problems/two-sum/
 * @Date 2022/9/23 10:09
 * @Created by 晓龙Oba
 */
public class TwoSum {

    public static void main(String[] args) {
        int target = 7;
        int[] nums = {1, 2, 3, 4, 5, 6};
        int[] ints = twoSum(nums, target);
        System.out.println(ints);
    }

    /*hash表解法*/
    private static int[] twoSum(int[] nums, int target) {
        // 首先创建一个hash表
        Map<Integer, Integer> intMap = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            // 判断hash表中是否已经存有目标元素
            Integer integer = intMap.get(target - nums[i]);
            if (integer != null) {
                // 若有则返回坐标
                return new int[]{integer, i};
            }
            // 如没有则存放元素,继续遍历
            intMap.put(nums[i], i);
        }
        return null;
    }

    /*枚举解法*/
    private static int[] twoSumByExhaustion(int[] nums, int target) {
        for (int i = 0; i < nums.length; i++) {
            for (int j = i + 1; j < nums.length; j++) {
                if (nums[j] == target - nums[i]) {
                    return new int[]{i, j};
                }
            }
        }
        return null;
    }
}
